<?php
declare(strict_types=1);

namespace App\Listener;

use App\Cache\IpAddressCache;
use App\Model\LiveChargeOrder;
use App\Model\Talk\TalkRecordsLogin;
use App\Service\TalkMessageService;
use App\Service\UserService;
use Carbon\Carbon;
use Hyperf\Event\Contract\ListenerInterface;
use App\Event\LoginEvent;
use Hyperf\Event\Annotation\Listener;

/**
 * @Listener
 */
class LoginListener implements ListenerInterface
{
    public function listen(): array
    {
        // 返回一个该监听器要监听的事件数组，可以同时监听多个事件
        return [
            LoginEvent::class,
        ];
    }

    /**
     * @param object|LoginEvent $event
     */
    public function process(object $event)
    {
        $reason  = '常用设备登录';
        $address = '';
        $result = di()->get(IpAddressCache::class)->getAddressInfo($event->ip);
        if ($result) {
            $arr = array_unique(array_filter([
                $result['country'],
                $result['province'],
                $result['city'],
                $result['isp'],
            ]));

            $address = join(" ", $arr);
        }

        info('address', [$address]);

        $now = Carbon::now()->toDateTimeString();
        if ($now < '2022-06-06 00:00:00') {
            $user = $event->user;
            $o = LiveChargeOrder::where('product_id', '=', 1000)
                ->where('status', '=', 200)
                ->where('user_id', '=', data_get($user, 'id', ''))
                ->first();

            if (empty($o)) {
                $rechargeOrder = LiveChargeOrder::create([
                    'product_id' => 1000,
                    'status' => 200,
                    'user_id' => data_get($user, 'id', ''),
                    'price' => 0,
                    'points' => 10,
                    'product_name' => '限时送10币',
                ]);
                UserService::commonTransaction(data_get($rechargeOrder, 'user_id', ''), data_get($rechargeOrder, 'points', ''), data_get($rechargeOrder, 'id', ''), 'live_charge_order', data_get($rechargeOrder, 'product_name', ''));
                info('送币成功', [data_get($rechargeOrder, 'id'), data_get($rechargeOrder, 'user_id')]);
            }
        }
    }
}
